package com.jigsaw.controller;

import com.jigsaw.model.MoviesCateEntity;
import com.jigsaw.model.MoviesInfoEntity;
import com.jigsaw.model.UserEntity;
import com.jigsaw.repository.MoviesCateRepository;
import com.jigsaw.repository.MoviesRepository;
import com.jigsaw.repository.UserRepository;
import com.jigsaw.util.JsonHelper;
import com.jigsaw.util.TokenProcessor;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by Jigsaw on 2016/4/10.
 */

@Controller
public class MoviesController implements HandlerInterceptor {

    @Autowired
    private MoviesRepository moviesRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private MoviesCateRepository moviesCateRepository;

    @RequestMapping(value = "/session/movies/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getFavMovies(@PathVariable("id") Integer movies_id) throws JSONException {
        MoviesInfoEntity movies = moviesRepository.findOne(movies_id);
        JSONObject moviesJson = new JSONObject();
        moviesJson.put("id", movies.getMid());
        moviesJson.put("ttt", movies.getTitle());
        MoviesCateEntity a = movies.getCateById();
        moviesJson.put("cate", a.getCategory());
        String tk = TokenProcessor.getInstance().generateToken();
        moviesJson.put("token", tk);
        return moviesJson.toString();
    }


    @RequestMapping(value = "/movies/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getMovies(@PathVariable("id") Integer movies_id) throws JSONException {
        MoviesInfoEntity movies = moviesRepository.findOne(movies_id);
        JSONObject moviesJson = new JSONObject();
        String moviesString = JsonHelper.MoviestoJson(moviesJson, movies);
        return moviesString;
    }

    @RequestMapping(value = "/movies/pagenum/{pnum}/pagesize/{psize}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String requestByPage(@PathVariable("pnum") Integer pnum, @PathVariable("psize") Integer psize) {
        Sort s = new Sort(Sort.Direction.DESC, "rating");
        Pageable pageable = new PageRequest(pnum, psize, s);
        Page<MoviesInfoEntity> result =  moviesRepository.findAll(pageable);
        List<String> temp = new ArrayList<>();
        return JsonHelper.MoviesToList(temp, result);
    }

    @RequestMapping(value = "/movies/user/{uid}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String FavoriteMovies(@PathVariable("uid") Integer uid) {
        UserEntity user = userRepository.findOne(uid);
        Set<MoviesInfoEntity> m =  user.getMoviesById();
        List<String> temp = new ArrayList<>();
        return JsonHelper.MoviesToList(temp, m);
    }

    @RequestMapping(value = "/movies/cate/{cid}/pagenum/{pnum}/pagesize/{psize}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String CateMovies(@PathVariable("cid") final Integer cid, @PathVariable("pnum") Integer pnum, @PathVariable("psize") Integer psize) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("defaultPersistenceUnit");
        EntityManager em = emf.createEntityManager();
        String sql = "SELECT * FROM `movies_info` WHERE cate_id = " + cid +" ORDER by rating DESC LIMIT " + pnum + "," + psize;
        javax.persistence.Query query = em.createNativeQuery(sql, MoviesInfoEntity.class);
        List<MoviesInfoEntity> res = query.getResultList();
        List<String> temp = new ArrayList<>();
        em.close();
        emf.close();
        return JsonHelper.MoviesToList(temp, res);



    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Integer uid = Integer.parseInt(httpServletRequest.getParameter("uid"));
        UserEntity user = userRepository.findOne(uid);
        String tk = user.getPrivateToken();
        if (!httpServletRequest.getParameter("tk").equals(tk)) {
            throw new Movies403Exception();
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
